﻿using Growatt.UploadPacktest;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TestFile.Model
{
    public class FileUrlService
    {
        private readonly IHttpClientFactory httpClientFactory;

        public FileUrlService(IHttpClientFactory httpClientFactory)
        {
            this.httpClientFactory = httpClientFactory;
        }
        /// <summary>
        /// 根据文件名获取文件下载路径
        /// </summary>
        /// <param name="appid">应用标识</param>
        /// <param name="token">用户访问令牌</param>
        /// <param name="encryptedUserId">加密用户ID</param>
        /// <param name="fileNames">文件名称数组</param>
        /// <returns>服务器返回的文件下载路径</returns>
        public  async Task<string> GetFileUrlsAsync(string appid, string token, string encryptedUserId, string[] fileNames)
        {
            string requestUrl = "http://oa.growatt.com:88/api/sap/getDownUrl";

            // 构建请求体
            string requestJson = "[";
            for (int i = 0; i < fileNames.Length; i++)
            {
                requestJson += $"{{\"fileName\": \"{fileNames[i]}\"}}";
                if (i < fileNames.Length - 1)
                {
                    requestJson += ",";
                }
            }
            requestJson += "]";

            // 创建HttpClient
            using (HttpClient client = this.httpClientFactory.CreateClient("OSS"))
            {
                client.DefaultRequestHeaders.Add("token", token);
                client.DefaultRequestHeaders.Add("appid", appid);
                client.DefaultRequestHeaders.Add("userid", encryptedUserId);

                HttpContent content = new StringContent(requestJson, Encoding.UTF8, "application/json");

                HttpResponseMessage response = await client.PostAsync(requestUrl, content);

                if (response.IsSuccessStatusCode)
                {
                    return await response.Content.ReadAsStringAsync();
                }
                else
                {
                    throw new HttpRequestException($"请求失败，状态码: {response.StatusCode}");
                }
            }
        }

        /// <summary>
        /// 解析 JSON 响应
        /// </summary>
        /// <param name="jsonResponse">JSON 响应字符串</param>
        /// <returns>解析后的文件下载路径响应对象</returns>
        public static FileUrlResponse ParseJsonResponse(string jsonResponse)
        {
            return JsonConvert.DeserializeObject<FileUrlResponse>(jsonResponse);
        }

        /// <summary>
        /// 验证响应状态
        /// </summary>
        /// <param name="response">文件下载路径响应对象</param>
        public static void ValidateResponse(FileUrlResponse response)
        {
            if (response == null)
            {
                throw new ArgumentException("Response cannot be null.");
            }

            if (response.Code != 1)
            {
                throw new InvalidOperationException($"Request failed with code: {response.Code}, message: {response.Message}");
            }

            if (!response.Message.Equals("SUCCESS", StringComparison.OrdinalIgnoreCase))
            {
                throw new InvalidOperationException($"Unexpected message: {response.Message}");
            }
        }
    }
}
